import { NextRequest, NextResponse } from 'next/server';
import { generateChallenge, submitChallenge } from '@/lib/challenge';
import { readWords, readCategories } from '@/lib/data';
import { verifyToken } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded) {
      return NextResponse.json(
        { success: false, message: '请先登录' },
        { status: 401 }
      );
    }

    const { categoryId, action, questions, userAnswers, timeSpent, mode } = await request.json();

    if (action === 'generate') {
      // 生成挑战
      const words = readWords();
      const categories = readCategories();
      
      try {
        const questions = generateChallenge(categoryId, words, categories, { fillOnly: mode === 'fill-only' });
        return NextResponse.json({ success: true, questions });
      } catch (error: any) {
        return NextResponse.json(
          { success: false, message: error.message },
          { status: 400 }
        );
      }
    } else if (action === 'submit') {
      // 提交挑战结果
      if (!questions || !userAnswers || timeSpent === undefined) {
        return NextResponse.json(
          { success: false, message: '缺少必要参数' },
          { status: 400 }
        );
      }

      const record = submitChallenge(decoded.userId, categoryId, questions, userAnswers, timeSpent);
      return NextResponse.json({ success: true, record });
    }

    return NextResponse.json(
      { success: false, message: '无效的操作' },
      { status: 400 }
    );
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '操作失败' },
      { status: 500 }
    );
  }
}

